package com.sc.security.service.impl;

import com.google.common.base.Joiner;
import com.sc.security.common.CacheKeyConstants;
import com.sc.security.service.RedisPool;
import com.sc.security.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;

@Service
@Slf4j
public class CacheServiceImpl implements CacheService {

    @Autowired
    private RedisPool redisPool;

    @Override
    public void saveCache(String value, int time, CacheKeyConstants prefix) {
        saveCache(value,time,prefix,null);
    }

    @Override
    public void saveCache(String value, int time, CacheKeyConstants prefix, String... keys) {
        if(value==null){
            return;
        }
        ShardedJedis shardedJedis = null;
        try {
            String cacheKey = generateCacheKey(prefix, keys);
            shardedJedis = redisPool.instance();
            shardedJedis.setex(cacheKey,time,value);
        }catch (Exception e){
            log.error("保存cache出错");
        }finally {
            redisPool.safeClose(shardedJedis);
        }
    }

    @Override
    public String getFromCache(CacheKeyConstants prefix, String... keys) {
        ShardedJedis shardedJedis = null;
        String cacheKey = generateCacheKey(prefix,keys);
        try {
            shardedJedis = redisPool.instance();
            String value = shardedJedis.get(cacheKey);
            return value;
        }catch (Exception e){
            log.error("取出缓存数据出错{}",cacheKey);
            return null;
        }finally {
            redisPool.safeClose(shardedJedis);
        }
    }


    private String generateCacheKey(CacheKeyConstants prefix,String... keys){
        String p = prefix.name();
        if(keys!=null&&keys.length>0){
            p+="_"+ Joiner.on("_").join(keys);
        }
        return p;
    }
}
